Skip to main content

Count 1's in Bit

There are two ways to count the number of ones in a given number:

  • The first approach involves using a bitwise AND operation to extract the last bit and check if it is equal to one. If it is, you can increment a counter. Then, you can right shift the number to move the bits and repeat the process until all ones have been counted.

  • The second approach involves performing an AND operation with num - 1 to remove the rightmost bit from the number. This process effectively removes all ones from the number, and the number of iterations required to do so will be the answer.

package main

import "fmt"


func countBits(num uint8) uint8 {

var count uint8 = 0
for num > 0 {
if num & 1 > 0 {
fmt.Printf("num & 1: %08b\n", (num & 1))
count++
}
num = num >> 1
fmt.Printf("num >> 1: %08b\n", num)
}
return count
}

func countBits2(num uint8) uint8 {
var count uint8 = 0
fmt.Printf("num: %08b\n", num)
for num > 0 {
fmt.Printf("num & (num - 1): %08b\n", (num & (num - 1)))
num = num & (num - 1)
count++
}
return count
}

func main() {

num := uint8(10) // Binary: 00001010
fmt.Printf("Original number: %08b\n", num)
fmt.Printf("Number of 1's in bits: %d\n", countBits(num))

fmt.Printf("Number of 1's in bits: %d\n", countBits2(num))

}

Output:

Original number: 00001010
num >> 1: 00000101
num & 1: 00000001
num >> 1: 00000010
num >> 1: 00000001
num & 1: 00000001
num >> 1: 00000000
Number of 1's in bits: 2